﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;
using System.Text;

namespace 加密算法
{
    public static class SM4Helper
    {
        // 示例密钥（16字节）
        public static string keyStr = "0123456789abcdef";
        public static byte[] keyBytes = Encoding.UTF8.GetBytes(keyStr);
        public static byte[] iv = new byte[16];

        /// <summary>
        /// SM4加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] EncryptSM4(byte[] plaintext)
        {
            IBufferedCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new SM4Engine()), new Pkcs7Padding());
            cipher.Init(true, new ParametersWithIV(new KeyParameter(keyBytes), iv));
            byte[] encryptedBytes = new byte[cipher.GetOutputSize(plaintext.Length)];
            int len = cipher.ProcessBytes(plaintext, 0, plaintext.Length, encryptedBytes, 0);
            len += cipher.DoFinal(encryptedBytes, len);
            Array.Resize(ref encryptedBytes, len);
            return encryptedBytes;
        }
        /// <summary>
        /// SM4解密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] DecryptSM4(byte[] ciphertext)
        {
            IBufferedCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new SM4Engine()), new Pkcs7Padding());
            cipher.Init(false, new ParametersWithIV(new KeyParameter(keyBytes), iv));
            byte[] decryptedBytes = new byte[cipher.GetOutputSize(ciphertext.Length)];
            int len = cipher.ProcessBytes(ciphertext, 0, ciphertext.Length, decryptedBytes, 0);
            len += cipher.DoFinal(decryptedBytes, len);
            Array.Resize(ref decryptedBytes, len);
            return decryptedBytes;
        }
    }
}